<template>
  <div class="p-m-page">
    <div class="p-m-pList">
      <div>
        <span class="p-m-p-title">
          文字列表
        </span>
        <span v-show="usingPoetry" class="p-m-p-using">
          使用中
        </span>
      </div>
      <div v-for="(poetry, index) in poetryList" :key="'p' + index" class="p-m-p-item" :class="poetryIndex === index ? 'active' : ''">
        <svg-icon v-if="poetry.useFlag === 0" icon-class="using" />
        <span class="p-m-p-span" @click="poetryChangeHandle(index)">
          {{ poetry.title }} - {{ poetry.vertical === 0 ? '水平' : '垂直' }}显示
        </span>
        <span class="p-m-p-btn">
          <el-button v-if="poetry.useFlag === 0" :disabled="buttonLoad" @click="cancelUsingPoetryHandle(index)" type="danger" size="mini" icon="el-icon-close" circle></el-button>
          <el-button v-else :disabled="buttonLoad" @click="usingPoetryHandle(index)" type="success" size="mini" icon="el-icon-check" circle></el-button>
          <el-button :disabled="buttonLoad" @click="deletePoetryHandle(index)" type="danger" size="mini" icon="el-icon-delete" circle></el-button>
        </span>
      </div>
    </div>
    <div class="p-m-content">
      <div class="p-m-c-left">
        <div class="p-m-c-l-title">
          文字输入
        </div>
        <el-form :model="poetryForm" :rules="poetryRules" ref="poetryForm" @keyup.enter.native="submitHandle" label-width="85px">
          <el-form-item label="文字标题" prop="title">
            <el-input v-model="poetryForm.title" maxLength="20" clearable
                      placeholder="请输入诗意文字标题" class="field-input">
            </el-input>
          </el-form-item>
          <el-form-item label="文字方向" prop="vertical">
            <el-radio-group v-model="poetryForm.vertical" size="mini">
              <el-radio :label="0" border>水平</el-radio>
              <el-radio :label="1" border>垂直</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-for="(field, index) in poetryForm.field"
            :label="'第' + (index + 1) + '行'"
            :key="field.key"
            :prop="'field.' + index + '.value'"
            :rules="{
               required: true, message: '文字内容不能为空', trigger: 'blur'
            }"
          >
            <el-input v-model.lazy="field.value" :maxLength="lineSize" clearable placeholder="请输入诗意文字内容" class="field-input"></el-input>
            <el-button @click.prevent="removeField(index)" >删除</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-if="poetryIndex === undefined" :disabled="buttonLoad" type="primary" @click="submitPoetryHandle">保存</el-button>
            <el-button v-if="poetryIndex !== undefined" :disabled="buttonLoad" type="primary" @click="updatePoetryHandle">修改</el-button>
            <el-button v-if="poetryIndex !== undefined" @click="clearFormHandle">取消</el-button>
            <el-button :disabled="poetryForm.field.length === fieldSize" @click="addField">新增一行</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="p-m-c-right">
        <div class="p-m-c-r-title">
          效果展示
        </div>
        <div>
          <!-- 水平显示 -->
          <div v-if="poetryForm.vertical === 0" class="level-content">
            <div v-for="(field, index) in poetryForm.field" :key="'p' + index" :class="index === 0 ? 'l-c-title' : 'l-c-item'">
              {{ field.value }}
            </div>
          </div>
          <!-- 垂直显示 -->
          <div v-else class="vertical-content">
            <div v-for="(field, index) in poetryForm.field" v-html="verticalHandle(index, field.value)" :key="'p' + index" :class="index === 0 ? 'v-c-title' : 'v-c-item'">
            </div>
          </div>
        </div>
      </div>
    </div>


  </div>
</template>

<script>

  export default {
    layout: 'admin',
    name: "admin-poem-manage",
    data() {
      return {
        // 用户诗意文字列表
        poetryList: [],
        // 用户选中的诗意文字下标
        poetryIndex: undefined,
        // 当前展示页码
        pageIndex: 1,
        // 当前页显示个数
        pageSize: 10,
        // 当前诗意文字列表数量
        totalNum: 0,
        // 是否使用诗意文字[true-使用 false-未使用]
        usingPoetry: false,
        // 用户诗意信息表单对象
        poetryForm: {
          // 诗意信息主键
          poetryId: '',
          // 空间标题
          title: '',
          // 显示方式[0-水平 1-垂直]
          vertical: 0,
          // 是否被使用[0-使用 1-未使用]
          useFlag: 1,
          field: [
            {
              key: Date.now(),
              value: ''
            }
          ],
        },
        // 按钮是否可被点击[true-不可被点击 false-可以被点击]
        buttonLoad: false,
        // 诗意文字表单校验规则
        poetryRules: {
          title: [
            { required: true, message: '诗意文字标题不能为空!', trigger: 'blur' }
          ],
        }
      }
    },
    computed: {
      // 主题颜色
      themeColor() {
        return this.$store.state.settings.theme;
      },
      // 最多可以添加的行数
      fieldSize() {
        return this.poetryForm.vertical === 0 ? 10 : 12
      },
      // 每行最多输入文字个数
      lineSize() {
        return this.poetryForm.vertical === 0 ? 20 : 15
      }
    },
    // async asyncData({ app, params, query}) {
    //   let { page } = await app.$axios.$get('/sys/poetry/list', { params: { page: 1, limit: 20 }})
    //   let { bool } = await app.$axios.$get('/sys/poetry/check/using')
    //   return {
    //     poetryList: page.list,
    //     totalNum: page.totalNum,
    //     usingPoetry: bool
    //   }
    // },
    created() {
      if (process.client) {

        this.initPoetryListHandle()
      }
    },
    methods: {
      // 初始化用户诗意文字信息列表
      initPoetryListHandle() {
        this.$axios.$get('/sys/poetry/list', { params: { page: 1, limit: 10 }})
          .then(({ data }) => {
            // 用户诗意信息分页数据
            let page = data.page
            // 用户是否使用诗意信息[true-使用 false-未使用]
            let useFlag = data.useFlag

            this.poetryList = page.list
            this.totalNum = page.totalNum
            this.usingPoetry = useFlag
          })
        .catch(() => {})
        .finally(() => {})
      },
      // 获取用户诗意文字列表事件
      getPoetryListHandle() {

        this.$axios.$get('/sys/poetry/list', { params: { page: this.pageIndex, limit: this.pageSize}})
          .then(({ data }) => {
            let page = data.page
            this.poetryList = page.list
            this.totalNum = page.totalNum
          })
          .catch(() => {})
      },
      // 诗意文字列表选择事件
      poetryChangeHandle(index) {
        if (this.poetryIndex === index) {
          // this.$refs.poetryForm.resetFields()
          // this.poetryIndex = undefined
          return
        }

        this.poetryIndex = index
        let poetryObj = this.poetryList[index]
        this.poetryForm.poetryId = poetryObj.poetryId
        this.poetryForm.title = poetryObj.title
        this.poetryForm.vertical = poetryObj.vertical
        this.poetryForm.useFlag = poetryObj.useFlag
        // 先清空原来的文字列表
        this.poetryForm.field = []
        let count = Date.now()
        poetryObj.dataList.forEach(info => {
          this.poetryForm.field.push( { key: count++, value: info })
        })

      },
      /**
       * 用户使用诗意信息事件
       * @param {Number} index 用户取消的诗意信息所在列表的下标
       */
      usingPoetryHandle(index) {
        let title = this.usingPoetry ? '当前已经有使用的诗意信息，你确定替换成当前选择的诗意信息吗？' : '确定要使用选择诗意信息吗？'

        this.$confirm(title, '选择确定', {
          confirmButtonText: '使用',
          cancelButtonText: '不使用',
          type: 'info'
        }).then(() => {
          // 按钮不可被点击
          this.buttonLoad = true
          // 根据下标获取将要使用的诗意信息
          let poetry = this.poetryList[index]
          this.$axios.$get('/sys/poetry/using', { params: { poetryId: poetry.poetryId }})
            .then(() => {
              this.notify('success',
                          this.usingPoetry ? '替换成功' : '使用成功',
                          this.usingPoetry ? '成功替换首页面显示诗意信息' : '诗意信息使用成功!')

              if (this.poetryIndex === index) {
                this.poetryForm.useFlag = 0
              }

              this.usingPoetry = true

              this.getPoetryListHandle()
            })
            .catch(() => {})
            .finally(() => {
              // 按钮恢复可点击
              this.buttonLoad = false
            })
        }).catch(() => {})
      },
      /**
       * 取消首页展示诗意信息事件
       * @param {Number} index 用户取消的诗意信息所在列表的下标
       */
      cancelUsingPoetryHandle(index) {
        this.$confirm('您确定要取消首页展示诗意信息吗？', '取消操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 按钮不可被点击
          this.buttonLoad = true
          // 根据下标获取准备取消使用的诗意信息
          let poetry = this.poetryList[index]
          this.$axios.$get('/sys/poetry/cancel/using', { params: { poetryId: poetry.poetryId }})
            .then(() => {
              this.notify('success', '操作成功', '取消首页展示诗意信息成功!')

              if (this.poetryIndex === index) {
                this.poetryForm.useFlag = 1
              }

              this.usingPoetry = false
              poetry.useFlag = 1
            })
            .catch(() => {})
            .finally(() => {
              // 按钮恢复可点击
              this.buttonLoad = false
            })
        }).catch(() => {})
      },
      /**
       * 删除诗意信息事件
       * @param {Number} index 诗意信息所在列表下标
       */
      deletePoetryHandle(index) {
        let poetry = this.poetryList[index]
        let title = poetry.useFlag === 0 ? '当前诗意文字正在使用中，确定要删除吗？' : '确定要删除诗意文字吗？'

        this.$confirm(title, '删除确定', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 按钮不可被点击
          this.buttonLoad = true

          this.$axios.$delete('/sys/poetry/delete', { params: { poetryId: poetry.poetryId }})
            .then(() => {
              this.notify('success', '操作成功', '诗意诗意删除成功!')

              if (poetry.useFlag === 0) {
                this.usingPoetry = false
              }
              if (this.poetryIndex === index) {
                this.clearFormHandle()
              }
              // 删除诗意信息
              this.poetryList.splice(index, 1)
            })
            .catch(() => {})
            .finally(() => {
              // 按钮恢复可点击
              this.buttonLoad = false
            })
        }).catch(() => {})
      },
      // 键盘回车事件
      submitHandle() {
        if (this.poetryIndex === undefined) {
          this.submitPoetryHandle()
        } else {
          this.updatePoetryHandle()
        }
      },
      // 诗意文字保存事件
      submitPoetryHandle() {
        this.$refs['poetryForm'].validate((valid) => {
          if (!valid) {
            return false
          }
          // 按钮不可被点击
          this.buttonLoad = true
          this.$confirm('是否直接使用提交的诗意信息?', '选择确定', {
            confirmButtonText: '使用',
            cancelButtonText: '不使用',
            type: 'info'
          })
          .then(() => {
            this.poetryForm.useFlag = 0
          })
          .catch(() => {})
          .finally(() => {
            // 添加用户诗意信息表单参数
            let poetryForm = {
              title: this.poetryForm.title,
              vertical: this.poetryForm.vertical,
              useFlag: this.poetryForm.useFlag,
              dataList: this.poetryForm.field.map(field => { return field.value })
            }
            this.$axios.$post('/sys/poetry/save', poetryForm)
              .then(() => {
                this.notify('success', '保存成功', '诗意信息保存成功!')

                // 重新获取用户诗意信息列表
                this.getPoetryListHandle()
                // 清空诗意信息表单
                this.clearFormHandle()
              }).catch(() => {})
              .finally(() => {
                // 按钮恢复可点击
                this.buttonLoad = false
              })
          })
        })
      },
      // 更新诗意信息事件
      updatePoetryHandle() {
        this.$refs['poetryForm'].validate((valid) => {
          if (!valid) {
            return false
          }
          // 按钮不可被点击
          this.buttonLoad = true

          let poetryForm = {
            poetryId: this.poetryForm.poetryId,
            title: this.poetryForm.title,
            vertical: this.poetryForm.vertical,
            useFlag: this.poetryForm.useFlag,
            dataList: this.poetryForm.field.map(field => { return field.value })
          }
          this.$axios.$post('/sys/poetry/update', poetryForm)
            .then(() => {
              this.notify('success', '修改成功', '诗意信息修改成功!')

              this.poetryList[this.poetryIndex] = poetryForm
            })
            .catch(() => {})
            .finally(() => {
              // 按钮恢复可点击
              this.buttonLoad = false
            })
        })
      },
      // 添加行
      addField() {
        this.poetryForm.field.push({
          key: Date.now(),
          value: ''
        })
      },
      /**
       * 删除文字行
       * @param {Number} index 待删除的文字行所在列表的下标
       */
      removeField(index) {
        if (this.poetryForm.field.length === 1) {
          this.notify('info', '提示', '内容行数不能为零')
          return
        }
        // 删除操作
        this.poetryForm.field.splice(index, 1)
        /*let lo = 0, hi = this.poetryForm.field.length - 1
        let fieldList = this.poetryForm.field
        while (lo <= hi) {
          let mid = (lo + hi) >> 1
          if (fieldList[mid].key > key) {
            hi = mid - 1;
          } else if (fieldList[mid].key < key) {
            lo = mid + 1;
          } else {
            fieldList.splice(mid, 1)  // 原地删除行
            break
          }
        }*/
      },
      // 清空表单事件
      clearFormHandle() {
        // 表单校验清空
        this.$refs.poetryForm.clearValidate()
        // 表单信息恢复初始值
        this.poetryForm = {
          poetryId: '',
          title: '',
          vertical: 0,
          useFlag: 1,
          field: [
            { key: Date.now(), value: '' }
          ],
        }
        // 用户选中诗意信息下标清空
        this.poetryIndex = undefined
      },
      // 文字列表显示方式改变事件
      verticalHandle(index, value) {
        let res = ''
        for (let i = 0; i < value.length; i++) {
          if (i === 0) {
            res += value[i]
          } else {
            res += '<br>' + value[i]
          }
        }
        return res
      },

    }
  }
</script>

<!--
  css字符对应
  c -> content
  l -> left,level
  m -> manage
  p -> poetry
  r -> right
  v -> vertical
-->
<style scoped>
  .p-m-page {
    position: relative;
    box-sizing: border-box;
  }
  .p-m-page:before, .p-m-page:after {
    display: table;
    content: "";
  }
  .p-m-page:after {
    clear: both;
  }
  .p-m-page .p-m-pList {
    width: 17%;
    float: left;
    box-sizing: border-box;
  }
  .p-m-page .p-m-content {
    width: 83%;
    float: left;
    position: relative;
    box-sizing: border-box;
  }
</style>

<style scoped>
  .p-m-pList .p-m-p-title {
    margin-left: 10px;
    margin-bottom: 7px;
    font-weight: bold;
  }
  .p-m-pList .p-m-p-using {
    margin-left: 10px;
    font-size: 13px;
    color: rgb(178,202,94);
  }
  .p-m-pList .p-m-p-item {
    width: 100%;
    line-height: 30px;
    font-size: 14px;
    padding: 5px 0;
    position: relative;
    cursor: pointer;
  }
  .p-m-p-item:hover {
    background-color: rgba(22,178,162, .1);
  }
  .p-m-p-item.active {
    background-color: rgba(22,178,162, .2);
  }
  .p-m-p-item .p-m-p-span {
    width: 70%;
    display: inline-flex;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .p-m-p-item:hover > .p-m-p-btn {
    display: inline-flex;
  }
  .p-m-p-item .p-m-p-btn {
    display: none;
    position: absolute;
    right: 5px;
  }
  .p-m-p-item .p-m-p-btn > button {
   margin-left: 3px;
  }
</style>

<style scoped>
  .p-m-content:before, .p-m-content:after {
    display: table;
    content: "";
  }
  .p-m-content:after {
    clear: both;
  }
  .p-m-content .p-m-c-left, .p-m-content .p-m-c-right {
    width: 50%;
    float: left;
    box-sizing: border-box;
  }
</style>


<style scoped>
  .p-m-c-left .p-m-c-l-title {
    margin-left: 10px;
    margin-bottom: 7px;
    font-weight: bold;
  }
  .p-m-c-left .field-input {
    width: 350px;
  }
</style>

<style scoped>
  .p-m-c-right .p-m-c-r-title {
    margin-bottom: 7px;
    font-weight: bold;
  }
  .p-m-c-right .vertical-content {
    display: flex;
  }
  .vertical-content .v-c-title {
    width:25px; text-align: center; font-size: 16px;font-weight:bold; margin-left: 5px;
  }
  .vertical-content .v-c-item {
    width:25px; text-align: center; font-size: 14px;
  }
  .p-m-c-right .level-content {

  }
  .level-content .l-c-title {
    text-align: center; font-size: 16px;font-weight:bold;
  }
  .level-content .l-c-item {
    font-size: 14px; margin-left: 5px; margin-top: 10px;
  }
</style>
